package com.yindian.cos.logging.elastic;

import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;

/**
 * 连接池，只维护一个实例，避免频繁创建
 *
 * @author zhangchuanhao
 * @date 2018/12/28
 */
public class ElasticsearchConnectionPool {

    private static ElasticsearchConnection elasticsearchConnection;

    public static ElasticsearchConnection getElasticsearchConnection(String host,
                                                                     int port,
                                                                     String index,
                                                                     String type,
                                                                     int maxActionsPerBulkRequest,
                                                                     int maxConcurrentBulkRequests,
                                                                     ByteSizeValue maxVolumePerBulkRequest,
                                                                     TimeValue flushInterval,
                                                                     String packageName) {
        newElasticsearchConnection(host,
                port,
                index,
                type,
                maxActionsPerBulkRequest,
                maxConcurrentBulkRequests,
                maxVolumePerBulkRequest,
                flushInterval,
                packageName);
        return elasticsearchConnection;
    }

    private static void newElasticsearchConnection(String host,
                                                   int port,
                                                   String index,
                                                   String type,
                                                   int maxActionsPerBulkRequest,
                                                   int maxConcurrentBulkRequests,
                                                   ByteSizeValue maxVolumePerBulkRequest,
                                                   TimeValue flushInterval,
                                                   String packageName) {
        if (elasticsearchConnection == null) {
            synchronized (ElasticsearchConnectionPool.class) {
                if (elasticsearchConnection == null) {
                    elasticsearchConnection = new ElasticsearchConnection(host,
                            port,
                            index,
                            type,
                            maxActionsPerBulkRequest,
                            maxConcurrentBulkRequests,
                            maxVolumePerBulkRequest,
                            flushInterval,
                            packageName
                    );
                }
            }
        }
    }

    public static void closeElasticsearchConnection() {
        elasticsearchConnection = null;
    }

}
